const router = require('koa-router')()
const writeJsonFile = require('write-json-file');
const loadJsonFile = require('load-json-file');
const { broadcastMessage, executeCommand, compressFolder, tospawn } = require('../utils/util');
const fs = require('fs');

const cwd = '/Users/guowenjun/yjst/mi'; // 运行命令的路径

router.prefix('/glb')

// 获取分支名称
router.get('/getBrancheName', async function (ctx, next) {
  const command = 'git rev-parse --abbrev-ref HEAD';
  broadcastMessage(command)
  const res = await executeCommand(command, { cwd });
  broadcastMessage(JSON.stringify(res.trim()))
  ctx.body = {
    code: 200,
    data: res.trim(),
  };
})
// 打包
router.get('/build', async function (ctx, next) {
  await tospawn('npm', ['run', 'build'], { cwd });
  await compressFolder(cwd + '/dist', cwd + '/dist.zip')
  broadcastMessage('打包完成')
  ctx.type = 'application/zip';
  ctx.attachment('dist.zip');
  ctx.body = fs.createReadStream(cwd + '/dist.zip');
})

// 切换git分支
router.get('/checkoutBranche', async function (ctx, next) {
  const { name } = ctx.request.query
  const command = 'git checkout ' + name;
  broadcastMessage(command)
  const res = await executeCommand(command, { cwd });
  broadcastMessage(JSON.stringify(res.trim()))
  const command2 = 'git pull origin ' + name;
  broadcastMessage(command2)
  const res2 = await executeCommand(command2, { cwd });
  broadcastMessage(JSON.stringify(res2.trim()))
  ctx.body = {
    code: 200,
    data: res2.trim(),
  };
})

// 获取所有git分支
router.get('/getBranches', async function (ctx, next) {
  const command = 'git branch -r';
  broadcastMessage(command)
  const res = await executeCommand(command, { cwd });
  broadcastMessage(res)
  const list = res.split('\n  ')
  const newlist = list.map(item => {
    if (!item.includes('->')) {
      return item.replace('  ', '').replace('\n', '').replace('origin/', '')
    }
  }).filter(item => item !== undefined);
  ctx.body = {
    code: 200,
    data: newlist,
  };
})

module.exports = router
